package com.dc.ai.controller;

import com.dc.ai.common.result.Result;
import com.dc.ai.entity.form.ForgetPasswordForm;
import com.dc.ai.entity.form.UserForm;
import com.dc.ai.entity.form.UserInfoForm;
import com.dc.ai.entity.po.LoginResult;
import com.dc.ai.security.utils.SecurityUtils;
import com.dc.ai.service.AuthService;
import com.dc.ai.service.SysUserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@Tag(name = "02.用户接口")
@RestController
@RequestMapping("/api/v1/users")
@RequiredArgsConstructor
public class SysUserController {

    private final SysUserService userService;


    private final AuthService authService;

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result userRegister(
            @RequestBody @Valid UserForm userForm
    ) {

        boolean result = userService.saveUser(userForm);

        return Result.judge(result);
    }

    @Operation(summary = "修改用户")
    @PutMapping(value = "/edit")
    public Result updateUser(@RequestBody @Validated UserInfoForm userInfoForm) {
        boolean result = userService.updateUser(userInfoForm);
        return Result.judge(result);
    }

    @Operation(summary = "注销用户信息")
    @DeleteMapping(value = "/{userId}")
    public Result removeUser(@PathVariable("userId") String userId) {

        userService.removeUser(userId);
        authService.logout();
        return Result.success();
    }


    @Operation(summary = "忘记密码")
    @PostMapping(value = "/forgetPassword")
    public Result forgetPassword(@RequestBody @Validated ForgetPasswordForm forgetPasswordForm) {

        boolean result = userService.forgetPassword(forgetPasswordForm);
        return Result.judge(result);
    }

    @Operation(summary = "设置密码")
    @PutMapping("/setPassword")
    public Result setPassword(
            @RequestParam String password) {

        String userId = SecurityUtils.getUserId();
        boolean ret = userService.setPassword(userId,password);
        if (ret) {
            authService.logout();
            return Result.success("密码设置成功，请重新登录");
        }
        return Result.failed("密码设置失败");

    }

}